package com.story.web.utils;

import javax.servlet.http.HttpServletRequest;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.captchastore.FastHashMapCaptchaStore;
import com.story.web.jcaptcha.service.GmailEngine;
import com.story.web.jcaptcha.service.MyManageableImageCaptchaService;

/*
 * @JCaptcha工具类
 * */
public class Jcaptcha {
	public static final MyManageableImageCaptchaService captchaSerivce = new MyManageableImageCaptchaService(
			new FastHashMapCaptchaStore(), new GmailEngine(), 180, 100000,
			75000);
	//验证当前请求输入的验证码否正确；并从CaptchaService中删除已经生成的验证码
	public static boolean validateResponse(HttpServletRequest request,
			String userCaptchaResponse) {
		if (request.getSession(false) == null)
			return false;
		boolean validated = false;
		try {
			String id = request.getSession().getId();
			validated = captchaSerivce.validateResponseForID(id,
					userCaptchaResponse).booleanValue();
		} catch (CaptchaServiceException e) {
			e.printStackTrace();
		}
		return validated;
	}
	//验证当前请求输入的验证码是否正确；但不从CaptchaService中删除已经生成的验证码（比如Ajax验证时可以使用，防止多次生成验证码）；
	public static boolean hasCaptcha(HttpServletRequest request,
			String userCaptchaResponse) {
		if (request.getSession(false) == null)
			return false;
		boolean validated = false;
		try {
			String id = request.getSession().getId();
			validated = captchaSerivce.hasCapcha(id, userCaptchaResponse);
		} catch (CaptchaServiceException e) {
			e.printStackTrace();
		}
		return validated;
	}
}
